export default class Snake{
  head: HTMLElement;
  bodies: HTMLCollection;
  element: HTMLElement;

  constructor(){
    // as 类型断言
    this.head = document.querySelector('#snake > div') as HTMLElement;

    this.bodies = document.getElementById('snake')!.getElementsByTagName('div');
    this.element = document.getElementById('snake')!;
  }

  // 获取蛇的坐标
  get X() {
    return this.head.offsetLeft;
  }
  get Y() {
    return this.head.offsetTop;
  }


  set X(value: number) {
    if (this.X == value) return;

    if (value < 0 || value > 290) {
      throw new Error('游戏结束')
    }

    //判断头和第二节坐标是否一样
    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value) {
      if (value > this.X) {
        value = this.X - 10;
      } else {
        value = this.X + 10;
      }
    }

    this.moveBody()
    this.head.style.left = `${value}px`;
    this.checkBump()
  }
  set Y(value: number) {
    if (this.Y == value) return;
    if (value < 0 || value > 290) {
      throw new Error('游戏结束')
    }

    //判断头和第二节坐标是否一样
    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
      if (value > this.Y) {
        value = this.Y - 10;
      } else {
        value = this.Y + 10;
      }
    }
    this.moveBody()
    this.head.style.top = `${value}px`;
    this.checkBump()
  }

  // 蛇身体增长
  addBody() {
    this.element.insertAdjacentElement("beforeend", document.createElement("div"))
  }

  moveBody() {
    for (let i=this.bodies.length-1; i>0; i--) {
      let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
      let y = (this.bodies[i-1] as HTMLElement).offsetTop;

      (this.bodies[i] as HTMLElement).style.left = `${x}px`;
      (this.bodies[i] as HTMLElement).style.top = `${y}px`
    }
  }

  checkBump() {
    for (let i = 1;i < this.bodies.length; i++) {
      let bd = (this.bodies[i] as HTMLElement);
      if (bd.offsetLeft == this.X && bd.offsetTop == this.Y) {
        console.log('身体装了')
        throw new Error('游戏结束')
      }
    }
  }
}